import React, { ReactElement, useEffect } from 'react';
import { View, Animated, Easing, Text, Image } from 'react-native';

import styles from './style';
import { phonePx, px } from '../../../../util/adapt';
import { avatar, openMicrophone } from '../../../../constant/resource';

const lines: {
  initAnimate: Animated.Value;
  animate: Animated.AnimatedInterpolation;
}[] = [];

for (let i = 0; i < 18; i += 1) {
  const initAnimate: Animated.Value = new Animated.Value(0);
  const animate = initAnimate.interpolate({
    inputRange: [0, 0.5, 1], // 输入值
    outputRange: [px(3), phonePx(6), px(3)] // 输出值
  });

  lines.push({ initAnimate, animate });
}

interface TalkingProps {
  headUrl: string;
  name: string;
}

export default ({ headUrl, name }: TalkingProps): ReactElement => {
  useEffect((): (() => void) => {
    const animations = lines.map(
      (item): Animated.CompositeAnimation =>
        Animated.loop(
          Animated.timing(item.initAnimate, {
            toValue: 1, // 最终值 为1，这里表示最大旋转 360度
            duration: 2000,
            easing: Easing.bounce,
            useNativeDriver: false
          })
        )
    );

    const timer = Animated.stagger(200, animations);
    timer.start();

    return (): void => {
      timer.stop();
    };
  }, []);

  return (
    <View style={styles.container}>
      <Image
        source={headUrl ? { uri: headUrl } : avatar}
        style={styles.icon}
        resizeMode="contain"
      />
      <View style={styles.content}>
        <Text style={styles.desc} numberOfLines={1}>
          {name} 连麦中
        </Text>
        <View style={styles.microphoneContent}>
          <Image
            source={openMicrophone}
            style={styles.microphone}
            resizeMode="contain"
          />
          {lines.map(
            (item): ReactElement => (
              <Animated.View style={[styles.line, { height: item.animate }]} />
            )
          )}
        </View>
      </View>
    </View>
  );
};
